package com.gton.lpl.filter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gton.lpl.common.annotation.NeedTokenByJWT;
import com.gton.lpl.common.annotation.SkipTokenByJWT;
import com.gton.lpl.common.diyerror.MyLoginException;
import com.gton.lpl.common.tools.IPAndMacTools;
import com.gton.lpl.entity.Gplogin;
import com.gton.lpl.service.GpRuleService;
import com.gton.lpl.service.GploginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Map;

/**
 * @description: JWT登录状态校验拦截器
 * @author: GuoTong
 * @createTime: 2021-10-05 15:40
 * @since JDK 1.8 OR 11
 **/
public class AuthenticationInterceptor implements HandlerInterceptor {
    /**
     * Description: HandlerInterceptor接口主要定义了三个方法
     * 1.boolean preHandle ()：
     * 预处理回调方法,实现处理器的预处理，第三个参数为响应的处理器,自定义Controller,返回值为true表示继续流程（如调用下一个拦截器或处理器）或者接着执行
     * postHandle()和afterCompletion()；false表示流程中断，不会继续调用其他的拦截器或处理器，中断执行。
     * <p>
     * 2.void postHandle()：
     * 后处理回调方法，实现处理器的后处理（DispatcherServlet进行视图返回渲染之前进行调用），此时我们可以通过modelAndView（模型和视图对象）对模型数据进行处理或对视图进行处理，modelAndView也可能为null。
     * <p>
     * 3.void afterCompletion():
     * 整个请求处理完毕回调方法,该方法也是需要当前对应的Interceptor的preHandle()的返回值为true时才会执行，也就是在DispatcherServlet渲染了对应的视图之后执行。用于进行资源清理。整个请求处理完毕回调方法。如性能监控中我们可以在此记录结束时间并输出消耗时间，还可以进行一些资源清理，类似于try-catch-finally中的finally，但仅调用处理器执行链中
     */

    @Autowired
    GploginService gploginService;

    @Autowired
    private GpRuleService gpRuleService;

    @Autowired
    @Qualifier("redisTemplateByMySelf")
    private RedisTemplate redisTemplate;

    /**
     * Description:  主要流程:
     * <p>
     * 1.从 http 请求头中取出 token，
     * 2.判断是否映射到方法
     * 3.检查是否有SkipTokenByJWT注解注释，有则跳过认证
     * 4.检查有没有需要用户登录的注解NeedTokenByJWT，有则需要取出并验证
     * 5.认证通过则可以访问，不通过会报相关错误信息
     */

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        // 从 http 请求头中取出 token
        String token = httpServletRequest.getHeader("token");
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        String url = httpServletRequest.getHeader("Origin");
        if (!StringUtils.isEmpty(url)) {
            httpServletResponse.setHeader("Access-Control-Allow-Origin", url);
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        }else{
            httpServletResponse.addHeader("Access-Control-Allow-Origin", "*");
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        //检查是否有SkipTokenByJWT注释，有则跳过认证
        if (method.isAnnotationPresent(SkipTokenByJWT.class)) {
            SkipTokenByJWT SkipTokenByJWT = method.getAnnotation(SkipTokenByJWT.class);
            if (SkipTokenByJWT.required()) {
                return true;
            }
        }
        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(NeedTokenByJWT.class)) {
            NeedTokenByJWT needTokenByJWT = method.getAnnotation(NeedTokenByJWT.class);
            if (needTokenByJWT.required()) {
                // 执行认证 无token，header里面的身份校验失败
                token = getTokenByGetOrCookie(httpServletRequest, token);
                // 执行认证 有token，header里面的身份通过则在token 中拿到 user id
                String username;
                try {
                    username = JWT.decode(token).getAudience().get(0);
                } catch (JWTDecodeException j) {
                    throw new MyLoginException("401,请重新登录");
                }
                QueryWrapper<Gplogin> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("username", username);
                Gplogin users = gploginService.getOne(queryWrapper);
                if (users == null) {
                    throw new MyLoginException("用户不存在，请重新登录");
                }
                // 校验token在该请求是否合法
                handlerTokenIslawful(httpServletRequest, token, needTokenByJWT, users);
                return true;
            }
        }
        return true;
    }

    /**
     * Description: 校验token在该请求是否合法
     * @author: GuoTong
     * @date: 2022-08-08 12:21:27
     * @param httpServletRequest
     * @param token
     * @param needTokenByJWT
     * @param users
     * @return:void
     */
    private void handlerTokenIslawful(HttpServletRequest httpServletRequest, String token, NeedTokenByJWT needTokenByJWT, Gplogin users) throws SocketException, UnknownHostException {
        // 验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(users.getPassword())).build();
        try {
            String loginName = users.getUsername();
            //获取请求的IP地址
            String ipAddr = IPAndMacTools.getIpAddr(httpServletRequest);
            //获取请求的Mac地址
            String localMac = IPAndMacTools.getLocalMac(ipAddr);
            //存入mac+name,mac去除：
            String IsRedisKeyByLifeName = localMac.replace(":", "").concat("#" + loginName);
            //Redis如果存在就判断token是否一致
            Map<String, Object> redisToken = redisTemplate.opsForHash().entries(IsRedisKeyByLifeName);
            if (redisToken == null || redisToken.size() == 0) {
                //如
                jwtVerifier.verify(token);
            } else {
                //如果redis中存在就校验redis中的果redis中不存在就校验token令牌令牌
                String redisTokenValue = redisToken.get("token").toString();
                assert StringUtils.equals(redisTokenValue, token) : "token错误";

                //上面验证完成登录状态，再次验证登录权限
                int rule = needTokenByJWT.rule();
                //1000普通用户 ，2000 会员  ，3000超级管理员 || 支持权限穿透
                //先查询缓存
                String redisRuleValue = redisToken.get("rule").toString();
                int gpRule = 0;
                try {
                    gpRule = Integer.parseInt(redisRuleValue);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
                if (gpRule < rule) {
                    throw new MyLoginException("权限不足，找管理员开通权限");
                }
            }
        } catch (AssertionError error) {
            throw new MyLoginException(error.getMessage());
        } catch (JWTVerificationException e) {
            throw new MyLoginException("用户登录状态已过期");
        }
    }

    /**
     * Description:  Header没有获取到token，处理Get请求从参数中尝试获取，从cookie中尝试获取
     * @author: GuoTong
     * @date: 2022-08-08 12:17:18
     * @param httpServletRequest
     * @param token
     * @return:java.lang.String
     */
    private String getTokenByGetOrCookie(HttpServletRequest httpServletRequest, String token) {

        if (StringUtils.isEmpty(token)) {
            boolean flag = false;
            //继续监测是不是get请求：路径上传递了参数
            String requestMethod = httpServletRequest.getMethod();
            if (requestMethod.equalsIgnoreCase("get")) {
                //从请求参数中尝试获取token
                token = httpServletRequest.getParameter("token");
                flag = (token != null);
            }
            //get请求路径上没传递token，那就去cookie里面找找
            if (!flag) {
                //请求参数中没有，就从cookie尝试获取token
                Cookie[] cookies = httpServletRequest.getCookies();
                if (cookies != null && cookies.length >= 1) {
                    for (Cookie cookie : cookies) {
                        if ("token".equals(cookie.getName())) {
                            token = cookie.getValue();
                            flag = true;
                        }
                    }
                }
            }
            //三种方式都校验完毕，再次校验是否token命中
            if (!flag || token == null) {
                throw new MyLoginException("检查结果未登录");
            }
        }
        return token;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }

}